/**
 * 
 */
package com.wegax.finprod.sender;

import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitOperations;

import com.wegax.finprod.application.Application;
import com.wegax.finprod.application.ApplicationFormType;


/**
 * @author wegax
 * 
 */
class ApplicationFormSenderImpl implements ApplicationFormSender {

	private static final Logger log = LoggerFactory.getLogger(ApplicationFormSenderImpl.class);

	private final RabbitOperations rabbitTemplate;

	ApplicationFormSenderImpl(final RabbitOperations rabbitTemplate) {
		this.rabbitTemplate = rabbitTemplate;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.wegax.finprod.sender.ApplicationFormSender#sendApplication(com.wegax.finprod.application.
	 * Application)
	 */
	@Override
	public String sendApplication(Application application) throws SendingException {
		log.info("About to send application: [{}]", application);
		String identifier = generateIdentifier(application.getCustomerIdentifier(), new Date());
		application.withApplicationFormIdentifier(identifier);
		log.debug("Application form identifier: [{}]", identifier);
		String destinationQueueName = prepareDestinationQueueName(application.getApplicationFormType());
		log.debug("Destination queue name: [{}] for application type: [{}]", destinationQueueName,
				application.getApplicationFormType());
		rabbitTemplate.convertAndSend(destinationQueueName, application);
		log.info("... application has been sent: [{}]", identifier);
		return identifier;
	}

	private String generateIdentifier(String customerIdentifier, Date date) {
		String value = customerIdentifier + date.getTime();
		return DigestUtils.md5Hex(value);
	}

	private String prepareDestinationQueueName(ApplicationFormType applicationFormType) {
		StringBuilder builder = new StringBuilder("queue.forms.");
		builder.append(applicationFormType.toString().toLowerCase().replaceAll("_", "."));
		return builder.toString();
	}

}
